

chrome.contextMenus.create({
    id: '1',
    title: '1.展开列表',
});

chrome.contextMenus.create({
    id: '2',
    title: '2.下一个',
});


chrome.contextMenus.onClicked.addListener(function (info, tab) {
    switch (info.menuItemId) {
        case '1':
            sendMessageToContentScript({ cmd: 'open', data: null }, null);
            break;
        case '2':
            sendMessageToContentScript({ cmd: 'next', data: null }, null);
            break;
        default:
            break;
    }
});


chrome.runtime.onInstalled.addListener(function () {
    chrome.declarativeContent.onPageChanged.removeRules(undefined, function () {
        chrome.declarativeContent.onPageChanged.addRules([
            {
                conditions: [
                    // 只有打开百度才显示pageAction
                    new chrome.declarativeContent.PageStateMatcher({ pageUrl: { urlContains: 'baidu.com' } })
                ],
                actions: [new chrome.declarativeContent.ShowPageAction()]
            }
        ]);
    });
});

//发送给contentjs
function sendMessageToContentScript(message, callback) {
    chrome.tabs.query({ active: true, currentWindow: true }, function (tabs) {
        chrome.tabs.sendMessage(tabs[0].id, message, function (response) {
            if (callback) callback(response);
        });
    });
}

chrome.webRequest.onBeforeRequest.addListener(details => {

    //只检查getContentStatusByCourseCode接口
    if (details.url.indexOf('/getContentStatusByCourseCode') !== -1) {
        //解析二进制
        let zyh = details.requestBody.formData.chapterCode[0];
    
        sendMessageToContentScript({ cmd: 'getContentStatusByCourseCode_req', data: zyh }, null);
    }

}, { urls: ['<all_urls>'] }, ['blocking', 'extraHeaders', 'requestBody']);


//监听消息
chrome.runtime.onMessage.addListener(function (message, sender, sendResponse) {

    switch (message.cmd) {
        case 'getContentByCourseCode':
            let content = message.data;
            if (content) {
                sendMessageToContentScript({ cmd: 'getContentByCourseCode', data: content }, null);
            }
            break;
        case 'getContentStatusByCourseCode':
            if (message.data) {
                sendMessageToContentScript({ cmd: 'getContentStatusByCourseCode', data: message.data }, null);
            }
            break;
        case 'Notice'://通知
            chrome.notifications.create(null, {
                type: 'basic',
                iconUrl: 'notice.png',
                title: '标题',
                message: message.data
            });
            break;
        default:
            break;
    }

})